package com.bob.debt.callback.factory;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.util.Map;

@Slf4j
public class CallbackProcessor implements BeanFactoryPostProcessor {

    private static final String CALLBACK_HANDLER_PACKAGE = "com.bob.debt.callback.impl";

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String, BeanPropertiesWrapper> maps = this.getDecoratorMap(CALLBACK_HANDLER_PACKAGE);
        CallbackContext context = new CallbackContext(maps);
        configurableListableBeanFactory.registerSingleton(CallbackContext.class.getName(), context);
    }

    public Map<String, BeanPropertiesWrapper> getDecoratorMap(String packageName) {
        Map<String, BeanPropertiesWrapper> decoratorMap = Maps.newHashMap();
        ClassScaner.scan(packageName, MsgLabelAdaptor.class).forEach(clazz -> {
            MsgLabelAdaptor adaptor = clazz.getAnnotation(MsgLabelAdaptor.class);
            BeanPropertiesWrapper beanPropertiesWrapper = new BeanPropertiesWrapper(clazz, StringUtils.uncapitalize(clazz.getSimpleName()));
            BeanPropertiesWrapper oldBeanProperties = decoratorMap.put(this.getKey(adaptor), beanPropertiesWrapper);
            if (oldBeanProperties != null) {
                throw new IllegalArgumentException("扫描到重复的ImmutablePair:" + this.getKey(adaptor));
            }
            log.info("init decoratorMap success ! data:{}", decoratorMap);
        });
        return decoratorMap;
    }

    public String getKey(MsgLabelAdaptor adaptor) {
        return adaptor.msgLabel();
    }
}
